<!-- 新增、查询功能  表单 静态-->
<form class="layui-form" action="" lay-filter="queryContent-filter">
    <div class="layui-form-item layui-row">
        <div class="layui-col-md1 layui-form-item">
            <button type="button" class="layui-btn layui-btn-primary layui-border-blue" id="addBtn">新增</button>
        </div>
        <div class=" layui-col-md2">
            <select name="type" lay-verify="required">
                <option value="">查询类别</option>
                <option value="name">姓名</option>
                <option value="age">年龄</option>
                <option value="gender">性别</option>
                <option value="score">成绩</option>
                <option value="address">住址</option>
            </select>
        </div>
        <div class="layui-col-md2">
            <input type="text" name="content" required lay-verify="required" placeholder="请输入查询内容" autocomplete="off"
                class="layui-input">
        </div>
        <div class="layui-col-md2">
            <label class="layui-form-label">查询</label>
            <div class="layui-input-block">
                <input type="checkbox" name="switch" lay-skin="switch" lay-filter="query-filter">
            </div>
        </div>

    </div>
</form>

<!-- 表格 -->
<table id="studentList" lay-filter="studentList-filter"></table>

<!-- 表格里按钮模板 -->
<script type="text/html" id="tableButtonGroup">
    <input type="button" value="编辑" class="layui-btn layui-btn-xs" lay-event="edit">
    <input type="button" value="删除" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
</script>

<!-- 新增功能弹出层模版 -->
<script type="text/html" id="addLayer">
<form class="layui-form" action="" lay-filter="add-filter">
    <div class="layui-form-item">
        <label class="layui-form-label">姓名</label>
        <div class="layui-input-block">
            <input type="text" name="name" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">年龄</label>
        <div class="layui-input-block">
            <input type="text" name="age" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="gender" value="男" title="男" checked>
            <input type="radio" name="gender" value="女" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">成绩</label>
        <div class="layui-input-block">
            <input type="text" name="score" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-block">
            <input type="text" name="address" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">电话</label>
        <div class="layui-input-block">
            <input type="text" name="phoneNumber" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>

</form>
</script>

<!-- 修改功能弹出层表单 -->
<script type="text/html" id="modifyLayer">
    <form class="layui-form" action="" lay-filter="modify-filter">
        <div class="layui-form-item">
            <label class="layui-form-label">学号</label>
            <div class="layui-input-block">
                <input type="text" name="id" required lay-verify="required"  autocomplete="off"
                class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required"  autocomplete="off"
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
                <input type="text" name="age" required lay-verify="required"  autocomplete="off"
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="男" title="男" checked>
                <input type="radio" name="gender" value="女" title="女" >
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">成绩</label>
            <div class="layui-input-block">
                <input type="text" name="score" required lay-verify="required"  autocomplete="off"
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <input type="text" name="address" required lay-verify="required"  autocomplete="off"
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-block">
                <input type="text" name="phoneNumber" required lay-verify="required"  autocomplete="off"
                    class="layui-input">
            </div>
        </div>
    </form>
    </script>



<!-- ----- 脚本 -------- -->
<script>
    let data = null; // 全局数据
    // 数据初始化
    function init() {
        let hasData = localStorage.getItem('students'); // 判断本地是否有数据
        if (hasData) {
            data = JSON.parse(localStorage.getItem('students'));
            console.log('本地有数据', data);
        } else {
            let arr = Mock.mock({
                "list|27": [{
                    "id|+1": 1,
                    "name": "@cname()",
                    "age|16-22": 1,
                    "gender|1": ["男", "女"],
                    "score|0-100": 1,
                    "address": "@county(true)",
                    "phoneNumber": /^1[3458]\d{9}$/
                }]
            }).list;
            localStorage.setItem('students', JSON.stringify(arr));
            data = arr;
            console.log('本地没有数据，已生成数据', data);
        }
    }
    init()

    // 表格渲染
    function render(arr = data) {
        table.render({
            elem: '#studentList'
            , data: arr //数据
            , page: true //开启分页
            , cols: [[ //表头
                { field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left' }
                , { field: 'name', title: '姓名', width: 120 }
                , { field: 'age', title: '年龄', width: 80, }
                , { field: 'gender', title: '性别', width: 80 }
                , { field: 'score', title: '成绩', width: 80, sort: true }
                , { field: 'address', title: '地址', sort: true }
                , { field: 'phoneNumber', title: '电话号码', }
                , { field: '', title: '操作', width: 200, templet: '#tableButtonGroup', } //这里的templet值是模板元素的选择器
            ]]
        });
    }
    render()

    //  默认表单渲染
    form.render(); //更新全部

    // 新增按钮点击弹出层
    $('#addBtn').click(function () {
        var index = layer.open({
            title: '新增'
            , content: $('#addLayer').html()
            , btn: ['确认新增', '取消']
            , btn1: function () { // 确认新增
                // console.log('数据：', data);
                var obj = form.val("add-filter"); // 从新增表单界面获取值
                // console.log(obj);
                if (obj.name) {
                    obj.id = data[data.length - 1].id + 1;
                    data.push(obj);
                    localStorage.setItem('students', JSON.stringify(data));
                    layer.msg('新增成功');
                    // 显示最后一页 renderLastPage(arr, page)
                    renderLastPage();
                }
                layer.close(index);
            }
            // , success: function (layero, index) {
            //     layui.laydate.render({
            //         elem: '#test1'//指定元素
            //     });
            // }
        });
        form.render();
    })

    // 测试 新增翻到最后一页
    function renderLastPage() {
        let n = $('.layui-table-page select').val();// 获取 n 条每页
        let pages = Math.ceil(data.length / n); // 数据总条数 / 每页显示 => 共几页
        console.log(`${n}条每页,共${pages}页`);

        table.render({
            elem: '#studentList'
            , data: data //数据
            , page: true //开启分页
            , cols: [[ //表头
                { field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left' }
                , { field: 'name', title: '姓名', width: 120 }
                , { field: 'age', title: '年龄', width: 80, }
                , { field: 'gender', title: '性别', width: 80 }
                , { field: 'score', title: '成绩', width: 80, sort: true }
                , { field: 'address', title: '地址', sort: true }
                , { field: 'phoneNumber', title: '电话号码', }
                , { field: '', title: '操作', width: 200, templet: '#tableButtonGroup', } //这里的templet值是模板元素的选择器
            ]]
            , page: {
                curr: pages
            }
        });
    }


    // 查询
    form.on('switch(query-filter)', function (o) {
        // console.log('data.elem:', data.elem); //得到checkbox原始DOM对象
        // console.log('data.elem.checked', data.elem.checked); //开关是否开启，true或者false
        // console.log('data.value', data.value); //开关value值，也可以通过data.elem.value得到
        // console.log('data.othis', data.othis); //得到美化后的DOM对象
        if (o.elem.checked) { // 开关开启
            var result = form.val("queryContent-filter"); // 从新增表单界面获取值 {type: 'age', content: '12', switch: 'on'}
            let { type, content } = result;
            if (content) {
                result = data.filter(item => item[type] == content); // 查询结果
                result.length ? render(result) : layer.msg('查询不到相关信息');
            }
        }
    });

    // 删除 修改
    table.on('tool(studentList-filter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var student = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        if (layEvent === 'del') { //删除
            let studentIndex = data.findIndex(item => item.id == student.id);
            layer.confirm(`学号: ${student.id}, 姓名: ${student.name}`, { title: '是否删除：' }, function (index) {
                data.splice(studentIndex, 1);
                localStorage.setItem('students', JSON.stringify(data));
                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                layer.close(index);
            });
        } else if (layEvent === 'edit') { //编辑
            // do something
            var index = layer.open({
                title: '编辑'
                , content: $('#modifyLayer').html()
                , btn: ['确认修改', '取消']
                , btn1: function () { // 确认修改
                    let studentIndex = data.findIndex(item => item.id == student.id); // 需要修改的学生的下标
                    var result = form.val("modify-filter"); // 获取修改表单内容
                    data.splice(studentIndex, 1, result);
                    localStorage.setItem('students', JSON.stringify(data)); // 存本地
                    //同步更新缓存对应的值
                    obj.update(result);
                    layer.close(index);
                }
            });
            form.val('modify-filter', student); // 设置值
            form.render();
        }
    });
</script>